package android.pot.com.smartcar.ui.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.BaseFragment;
import android.pot.com.smartcar.base.CommonAdapter;
import android.pot.com.smartcar.base.CommonRecycleAdapter;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.RecycleViewHolder;
import android.pot.com.smartcar.base.ViewHolder;
import android.pot.com.smartcar.config.MyConfig;
import android.pot.com.smartcar.entity.HomeEntity;
import android.pot.com.smartcar.entity.UserInfo;
import android.pot.com.smartcar.tool.LaunchTimer;
import android.pot.com.smartcar.tool.LocationHelper;
import android.pot.com.smartcar.tool.LoginTool;
import android.pot.com.smartcar.ui.find.PhotoActivity;
import android.pot.com.smartcar.ui.home.activity.ProductDetailActivity;
import android.pot.com.smartcar.ui.home.activity.ShopListActivity;
import android.pot.com.smartcar.ui.login.LoginsActivity;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.PermissionUtil;
import android.pot.com.smartcar.util.TextCheckUtil;
import android.pot.com.smartcar.widget.ListViewForScrollView;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bingoogolapple.bgabanner.BGABanner;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by zhaoshilu on 2017/11/14.
 */
public class HomesFragment extends BaseFragment  implements EasyPermissions.PermissionCallbacks, LocationHelper.LocationCallBack {

    private static HomesFragment instance;

    private View view;

    private Context context;

    private BGABanner mStackBanner;

    private RefreshLayout refreshLayout;

    private List<String> bannerUrl = new ArrayList<>();

    private ArrayList<String> linkUrl = new ArrayList<>();

    private boolean showLoading = true;

    private int curPage = 1;

    private int pageCount;

    private boolean needClear = true;

    private RecyclerView rc_view;

    private ListViewForScrollView lv_home;

    private CommonRecycleAdapter navAdapter;

    private CommonAdapter mAdapter;

    List< HomeEntity.GoodsData> navModels = new ArrayList<>();

    List< HomeEntity.ServiceData> listModels = new ArrayList<>();

    private LocationHelper helper;

    private boolean isFrist = true;

    public static HomesFragment instance() {
        if (instance == null) {
            instance = new HomesFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_homes, container, false);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initView(view);
        addListener();
        initData();

        return view;

    }


    @Override
    public void onResume() {
        super.onResume();
        if (mStackBanner!=null){
            mStackBanner.startAutoPlay();
        }


    }

    @Override
    public void onPause() {
        super.onPause();

        if (mStackBanner!=null) {
            mStackBanner.stopAutoPlay();
        }
    }


    @Override
    protected void initView(View view) {
        mStackBanner = (BGABanner) view.findViewById(R.id.home_kanner);
        rc_view = (RecyclerView) view.findViewById(R.id.rv);
        lv_home = (ListViewForScrollView) view.findViewById(R.id.lv_home);
        initRefreshView();
        initBannerView();
        initNavView();
        initRecommandView();
     }

    private void initNavView(){

        navAdapter = new CommonRecycleAdapter<HomeEntity.GoodsData>(context, R.layout.gridcell_homes,navModels) {
            @Override
            public void convert(RecycleViewHolder holder, final HomeEntity.GoodsData data) {
                switch (holder.getMPostion()%4){
                    case 0:
                        holder.setBackgroundRes(R.id.rl_outer,R.mipmap.img_oil1);
                        break;
                    case 1:
                        holder.setBackgroundRes(R.id.rl_outer,R.mipmap.img_oil2);
                        break;
                    case 2:
                        holder.setBackgroundRes(R.id.rl_outer,R.mipmap.img_oil3);
                        break;
                    case 3:
                        holder.setBackgroundRes(R.id.rl_outer,R.mipmap.img_oil4);
                        break;
                }
                holder.setText(R.id.tv_title, TextCheckUtil.CheckString(data.getOriginal_price()));
                holder.setText(R.id.tv_price,"¥"+ TextCheckUtil.formate2Money(data.getSpecial_price()));
                holder.setImageByUrl(R.id.iv_img, data.getPlan());
                holder.setOnClickListener(R.id.rl_outer, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (TextUtils.isEmpty(LoginTool.getToken())) {
                            startAct(context, LoginsActivity.class);
                            return;
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("productId",data.getGoods_id());
                        startAct(context, ProductDetailActivity.class,bundle);
                    }
                });
            }
        };
         GridLayoutManager layoutManager = new GridLayoutManager(context, 4);
//        new LinearLayoutManager(context, LinearLayout.HORIZONTAL,false)
        rc_view.setLayoutManager(layoutManager);//设置布局管理器
        rc_view.setAdapter(navAdapter);
    }
    private void initRecommandView() {

        mAdapter = new CommonAdapter<HomeEntity.ServiceData>(context, listModels, R.layout.listcell_homes) {
            @Override
            public void convert(ViewHolder helper, HomeEntity.ServiceData item) {
                helper.setText(R.id.tv_title,item.getName());
                switch (item.getId()){
                    case 1:
                        helper.setText(R.id.tv_englist,"Car maintenance");
//                        helper.setImageResource(R.id.iv_img,R.mipmap.img_oil);
                        helper.setBackgroundResource(R.id.rl_outer,R.mipmap.img_list1);
                        helper.setBackgroundResource(R.id.rl_img,R.mipmap.img_cricle1);
                        helper.setImageByUrl(R.id.iv_img,MyConfig.IMG_URL+TextCheckUtil.CheckString(item.getImg_url()));
                        break;
                    case 2:
                        helper.setText(R.id.tv_englist,"Tire services");
//                        helper.setImageResource(R.id.iv_img,R.mipmap.img_luntai);
                        helper.setBackgroundResource(R.id.rl_outer,R.mipmap.img_list2);
                        helper.setBackgroundResource(R.id.rl_img,R.mipmap.img_cricle2);
                        helper.setImageByUrl(R.id.iv_img,MyConfig.IMG_URL+TextCheckUtil.CheckString(item.getImg_url()));

                        break;
                    case 3:
                        helper.setText(R.id.tv_englist,"Car cleaning");
//                        helper.setImageResource(R.id.iv_img,R.mipmap.img_car);
                        helper.setBackgroundResource(R.id.rl_outer,R.mipmap.img_list3);
                        helper.setBackgroundResource(R.id.rl_img,R.mipmap.img_cricle3);
                        helper.setImageByUrl(R.id.iv_img,MyConfig.IMG_URL+TextCheckUtil.CheckString(item.getImg_url()));

                        break;
                    case 4:
                        helper.setText(R.id.tv_englist,"Car Repair");
//                        helper.setImageResource(R.id.iv_img,R.mipmap.img_weixiu);
                        helper.setBackgroundResource(R.id.rl_outer,R.mipmap.img_list4);
                        helper.setBackgroundResource(R.id.rl_img,R.mipmap.img_cricle4);
                        helper.setImageByUrl(R.id.iv_img,MyConfig.IMG_URL+TextCheckUtil.CheckString(item.getImg_url()));

                        break;
                }


            }
        };
        lv_home.setAdapter(mAdapter);
    }

    private void initRefreshView() {
        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                needClear = true;
                showLoading = false;
                curPage = 1;
                requestData();

            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                curPage++;
                needClear = false;
                showLoading = false;

            }
        });


    }


    private void initBannerView() {

        mStackBanner.setAdapter(new BGABannerAdapter(context,2));

        mStackBanner.setDelegate(new BGABanner.Delegate<ImageView, String>() {
            @Override
            public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
                if (linkUrl.size()>0) {
//                    Bundle bundle = new Bundle();
//                    bundle.putStringArrayList("img", linkUrl);
//                    bundle.putInt("CurPic",position);
//                    bundle.putBoolean("single",true);
//                    startAct(context, PhotosScanActivity.class, bundle);

                    Bundle bundle = new Bundle();
                    bundle.putString("img",linkUrl.get(position));
                    startAct(context, PhotoActivity.class, bundle);
                }

            }
        });
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }




    @Override
    protected void addListener() {
        lv_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (TextUtils.isEmpty(LoginTool.getToken())) {
                    startAct(context, LoginsActivity.class);
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("cid",listModels.get(i).getId()+"");
                bundle.putString("cname",listModels.get(i).getName());
                startAct(context, ShopListActivity.class,bundle);
            }
        });
    }





    @Override
    protected void initData() {
        LocationTask();
        requestData();


    }
    @Override
    public void onDestroy() {
        helper.stop();
        super.onDestroy();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_LOCATION_PERM) {

        }
    }


    /**
     * 请求位置权限码
     */
    public static final int REQUEST_LOCATION_PERM = 101;

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            PermissionUtil.openPermissionDialog(context,getString(R.string.request_location_permission));

        }
    }

    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @AfterPermissionGranted(REQUEST_LOCATION_PERM)
    public void LocationTask() {
        if (EasyPermissions.hasPermissions(context, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // Have permission, do the thing!
                startLocation();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, getString(R.string.request_location),
                    REQUEST_LOCATION_PERM, Manifest.permission.ACCESS_COARSE_LOCATION);
        }
    }

    //开启定位

    public void startLocation() {

        helper = LocationHelper.getInstance();

        helper.setCallBack(this);

        helper.start();

    }

    //定位返回的数据
    @Override
    public void callBack(String addr, String streetnumber, final double lat, final double lng, String district, String street, final String city, String province) {

        UserInfo.instance().setLat(lat+"");
        UserInfo.instance().setLng(lng+"");

    }

    private void requestData() {

        Map<String, String> map = new HashMap<>();

        Action.get().home(context, map, new MyResponseHandler() {
            @Override
            public void onSuccess(String message, JSONObject response) {
                bannerUrl.clear();
                linkUrl.clear();
                HomeEntity homeEntity =  GsonUtil.getObject(response.toString(), HomeEntity.class);
                for (HomeEntity.AdData data: homeEntity.getAd()){
                    bannerUrl.add(MyConfig.IMG_URL+data.getImg_url());
                    linkUrl.add(MyConfig.IMG_URL+data.getDetail_img());
                }
                UserInfo.instance().setLogo(homeEntity.getLogo().getImg_url());
                mStackBanner.setData(bannerUrl, null);
                navModels.clear();
                navModels.addAll(homeEntity.getGoods());

                listModels.clear();
                listModels.addAll(homeEntity.getService());
                if (isFrist){
                    isFrist = false;
                    LaunchTimer.endRecord();
                }
                navAdapter.notifyDataSetChanged();
                mAdapter.notifyDataSetChanged();
                refreshLayout.finishRefresh();
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                refreshLayout.finishRefresh();
            }
        });
    }



}